package manager;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;

import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.grandstream.wavesdk.WaveErrorCode;
import com.grandstream.wavesdk.WaveSDK;
import com.grandstream.wavesdk.bean.WaveCancelMeetingParams;
import com.grandstream.wavesdk.bean.WaveDialParams;
import com.grandstream.wavesdk.bean.WaveJoinMeetingByLinkParams;
import com.grandstream.wavesdk.bean.WaveJoinMeetingParams;
import com.grandstream.wavesdk.bean.WaveLoginParams;
import com.grandstream.wavesdk.bean.WaveMeeting;
import com.grandstream.wavesdk.bean.WaveMeetingNowParams;
import com.grandstream.wavesdk.bean.WaveMember;
import com.grandstream.wavesdk.bean.WaveScheduleMeetingList;
import com.grandstream.wavesdk.bean.WaveScheduleMeetingParams;
import com.grandstream.wavesdk.bean.WaveScheduleMember;
import com.grandstream.wavesdk.listener.WaveCancelMeetingListener;
import com.grandstream.wavesdk.listener.WaveDialListener;
import com.grandstream.wavesdk.listener.WaveEndMeetingListener;
import com.grandstream.wavesdk.listener.WaveEventListener;
import com.grandstream.wavesdk.listener.WaveJoinMeetingByLinkListener;
import com.grandstream.wavesdk.listener.WaveJoinMeetingListener;
import com.grandstream.wavesdk.listener.WaveLoginListener;
import com.grandstream.wavesdk.listener.WaveLogoutListener;
import com.grandstream.wavesdk.listener.WaveMeetingListListener;
import com.grandstream.wavesdk.listener.WaveMeetingNowListener;
import com.grandstream.wavesdk.listener.WaveScheduleMeetingListener;

import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

import listener.LogoutListener;
import listener.SdkListener;

public class WaveManager {
    @SuppressLint("StaticFieldLeak")
    private static WaveManager instance;

    private final Context context;
    private final JSONObject emptyMap = new JSONObject();
    private final WaveSDK waveSDK;
    private LogoutListener logoutListener;
    //是否添加了监听
    private boolean isAddLogoutListener = false;

    public WaveManager(Context context){
        this.context = context;
        waveSDK = WaveSDK.instance();
        waveSDK.initialize(context);
        waveSDK.showCallingBackButton(false);
    }

    public static WaveManager getInstance(Context context) {
        if(instance == null){
            instance = new WaveManager(context);
        }
        return instance;
    }

    /**
     * 监听状态
     */
    public void setWaveEventListener(LogoutListener listener) {
        if (!isAddLogoutListener) {
            logoutListener = listener;
            waveSDK.addEventListener(waveEventListener);
            if (logoutListener != null) {
                logoutListener.success();
            }
            isAddLogoutListener = true;
        }
    }

    /**
     * 移除状态监听
     */
    public void removeWaveEventListener() {
        logoutListener = null;
        waveSDK.removeEventListener(waveEventListener);
        isAddLogoutListener = false;
    }

    /**
     * 登录账号
     */
    public void login(String server, String account, String password, SdkListener listener) {
        WaveLoginParams params = new WaveLoginParams();
        params.server = server;
        params.account = account;
        params.password = password;
        waveSDK.login(params, new WaveLoginListener() {
            @Override
            public void onLogin(int i, String s) {
                String message = s;
                if (i == WaveErrorCode.ERR_SUCCESS) {
                    message = "登录成功";
                }
                if (listener != null) {
                    listener.onResult(i, emptyMap, message);
                }
            }
        });
    }

    /**
     * 退出登录
     */
    public void logout(SdkListener listener) {
        waveSDK.logout(new WaveLogoutListener() {
            @Override
            public void onLogout(int i, String s) {
                if (listener != null) {
                    listener.onResult(i, emptyMap, s);
                }
            }
        });
    }

    /**
     * 链接入会
     */
    public void joinMeetingByLink(String link, String userName, String password, boolean isOpenCamera, SdkListener listener) {
        WaveJoinMeetingByLinkParams params = new WaveJoinMeetingByLinkParams();
        params.link = link;
        params.userName = userName;
        params.password = password;
        params.isOpenCamera = isOpenCamera;
        waveSDK.joinMeetingByLink(context, params, new WaveJoinMeetingByLinkListener() {
            @Override
            public void onJoinMeetingByLink(int i, String s) {
                if (listener != null) {
                    listener.onResult(i, emptyMap, s);
                }
            }
        });
    }

    /**
     * 呼叫号码
     */
    public void dial(String number, boolean isOpenCamera, SdkListener listener) {
        WaveDialParams params = new WaveDialParams();
        params.number = number;
        params.isOpenCamera = isOpenCamera;
        waveSDK.dial(context, params, new WaveDialListener() {
            @Override
            public void onDial(int i, String s) {
                if (listener != null) {
                    listener.onResult(i, emptyMap, s);
                }
            }
        });
    }


    /**
     * 加入会议
     */
    public void joinMeeting(String meetingNumber, boolean isOpenCamera, SdkListener listener) {
        WaveJoinMeetingParams params = new WaveJoinMeetingParams();
        params.meetingNumber = meetingNumber;
        params.isOpenCamera = isOpenCamera;
        waveSDK.joinMeeting(context, params, new WaveJoinMeetingListener() {
            @Override
            public void onJoinMeeting(int i, String s) {
                if (listener != null) {
                    listener.onResult(i, emptyMap, s);
                }
            }
        });

    }

    /**
     * 即时会议
     */
    public void meetingNow(String subject, boolean isOpenCamera, JSONObject[] members, SdkListener listener) {
        WaveMeetingNowParams params = new WaveMeetingNowParams();
        params.subject = subject;
        params.isOpenCamera = isOpenCamera;
        if (members.length > 0) {
            List<WaveMember> memberList = new ArrayList<>();
            for (JSONObject jsonObject : members) {
                WaveMember member = new WaveMember();
                if (jsonObject.containsKey("number") && !TextUtils.isEmpty(jsonObject.getString("number"))) {
                    member.number = jsonObject.getString("number");
                }
                if (jsonObject.containsKey("email") && !TextUtils.isEmpty(jsonObject.getString("email"))) {
                    member.email = jsonObject.getString("email");
                }
                memberList.add(member);
            }
            params.memberList = memberList;
        }
        waveSDK.meetingNow(params, new WaveMeetingNowListener() {
            @Override
            public void onMeetingNow(int i, String s) {
                if (listener != null) {
                    listener.onResult(i, emptyMap, s);
                }
            }
        });
    }

    /**
     * 预约会议
     */
    public void scheduleMeeting(JSONObject meetingParams, ArrayList<JSONObject> members, SdkListener listener) {
        // 会议开会时间
        String startTime = meetingParams.getString("startTime");
        // 会议结束时间
        String endTime = meetingParams.getString("endTime");
        // 时区
        String timeZone = TimeZone.getDefault().getDisplayName();
        // 构建预约会议成员
        ArrayList<WaveScheduleMember> memberList = new ArrayList<>();
        if (!members.isEmpty()) {
            for (JSONObject jsonObject : members) {
                WaveScheduleMember member = new WaveScheduleMember();
                if (jsonObject.containsKey("number") && !TextUtils.isEmpty(jsonObject.getString("number"))) {
                    member.number = jsonObject.getString("number");
                }
                if (jsonObject.containsKey("email") && !TextUtils.isEmpty(jsonObject.getString("email"))) {
                    member.email = jsonObject.getString("email");
                }
                if (jsonObject.containsKey("isHost") && !TextUtils.isEmpty(jsonObject.getString("isHost"))) {
                    member.isHost = jsonObject.getBoolean("isHost");
                }
                memberList.add(member);
            }
        }
        // 构建预约会议参数
        WaveScheduleMeetingParams params = new WaveScheduleMeetingParams();
        //会议室主题
        params.subject = meetingParams.getString("subject");
        //会议描述
        if (meetingParams.containsKey("description") && !TextUtils.isEmpty(meetingParams.getString("description"))) {
            params.description = meetingParams.getString("description");
        }
        //会议主持码
        if (meetingParams.containsKey("hostCode") && !TextUtils.isEmpty(meetingParams.getString("hostCode"))) {
            params.hostCode = meetingParams.getString("hostCode");
        }
        //会议密码
        if (meetingParams.containsKey("password") && !TextUtils.isEmpty(meetingParams.getString("password"))) {
            params.password = meetingParams.getString("password");
        }
        params.startTime = startTime;
        params.endTime = endTime;
        params.timeZone = timeZone;
        //会议即将开始邮件提醒时间
        if (meetingParams.containsKey("emailRemindTime") && !TextUtils.isEmpty(meetingParams.getString("emailRemindTime"))) {
            params.emailRemindTime = meetingParams.getInteger("emailRemindTime");
        }
        //会议室开始时是否呼叫预约会议成员
        if (meetingParams.containsKey("callMember") && !TextUtils.isEmpty(meetingParams.getString("callMember"))) {
            params.callMember = meetingParams.getBoolean("callMember");
        }
        //是否允许解除"主持人禁音"
        if (meetingParams.containsKey("allowUserUnmuted") && !TextUtils.isEmpty(meetingParams.getString("allowUserUnmuted"))) {
            params.allowUserUnmuted = meetingParams.getBoolean("allowUserUnmuted");
        }
        //是否允许与会者邀请成员
        if (meetingParams.containsKey("userInvite") && !TextUtils.isEmpty(meetingParams.getString("userInvite"))) {
            params.userInvite = meetingParams.getBoolean("userInvite");
        }
        //预约会议成员
        if (!memberList.isEmpty()) {
            params.memberList = memberList;
        }
        //会议循环类型
        if (meetingParams.containsKey("cycleType") && !TextUtils.isEmpty(meetingParams.getString("cycleType"))) {
            params.cycleType = meetingParams.getString("cycleType");
        }

        waveSDK.scheduleMeeting(params, new WaveScheduleMeetingListener() {
            @Override
            public void onScheduleMeeting(int i, String s) {
                if (listener != null) {
                    listener.onResult(i, emptyMap, s);
                }
            }
        });
    }

    /**
     * 会议列表
     */
    public void getScheduleMeetingList(int page, SdkListener listener) {
        waveSDK.getScheduleMeetingList(page, new WaveMeetingListListener() {
            @Override
            public void onScheduleMeetingList(int i, @Nullable WaveScheduleMeetingList waveScheduleMeetingList) {
                JSONObject data = new JSONObject();
                if (waveScheduleMeetingList != null) {
                    int totalPage = waveScheduleMeetingList.getTotalPage();
                    int currentPage = waveScheduleMeetingList.getCurrentPage();
                    int total = waveScheduleMeetingList.getTotal();
                    List<WaveMeeting> list = waveScheduleMeetingList.getMeetingList();
                    List<JSONObject> meetings = new ArrayList<>();
                    if (!list.isEmpty()) {
                        for (WaveMeeting meeting : list) {
                            JSONObject map = new JSONObject();
                            map.put("meetingId", meeting.getMeetingId());
                            map.put("meetingNumber", meeting.getMeetingNumber());
                            map.put("meetingState", meeting.getMeetingState());
                            map.put("meetingType", meeting.getMeetingType());
                            map.put("creator", meeting.getCreator());
                            map.put("description", meeting.getDescription());
                            map.put("cycleType", meeting.getCycleType());
                            map.put("endTime", meeting.getEndTime());
                            map.put("host", meeting.getHost());
                            map.put("startTime", meeting.getStartTime());
                            map.put("subject", meeting.getSubject());
                            meetings.add(map);
                        }
                    }
                    data.put("totalPage", totalPage);
                    data.put("currentPage", currentPage);
                    data.put("total", total);
                    data.put("meetings", meetings);
                }
                if (listener != null) {
                    listener.onResult(i, data, "");
                }
            }
        });
    }

    /**
     * 取消会议
     */
    public void cancelMeeting(String meetingId, String meetingNumber, boolean cancelNextMeeting, SdkListener listener) {
        WaveCancelMeetingParams params = new WaveCancelMeetingParams();
        params.meetingId = meetingId;
        params.meetingNumber = meetingNumber;
        params.cancelNextMeeting = cancelNextMeeting;
        waveSDK.cancelMeeting(params, new WaveCancelMeetingListener() {
            @Override
            public void onCancelMeeting(int i, String s) {
                if (listener != null) {
                    listener.onResult(i, emptyMap, s);
                }
            }
        });
    }

    /**
     * 结束会议
     */
    public void endMeeting(String meetingNumber, SdkListener listener) {
        waveSDK.endMeeting(meetingNumber, new WaveEndMeetingListener() {
            @Override
            public void onEndMeeting(int i, String s) {
                if (listener != null) {
                    listener.onResult(i, emptyMap, s);
                }
            }
        });
    }

    private final WaveEventListener waveEventListener = new WaveEventListener() {
        @Override
        public void logout(int i, String s) {
            if (logoutListener != null) {
                logoutListener.logout(i, s);
            }
        }
    };
}
